package com.atguigu.tingshu.common.config.pool;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@ConfigurationProperties(prefix = "tingshu.threadpool")
@Data
public class ServiceThreadPoolConfig {
    private Integer corePoolSize;
    private Integer maxPoolSize;
    private Integer queueCapacity;
    private Long keepAliveSeconds;


    private static Integer CORE_POOL_SIZE;
    private static Integer MAX_POOL_SIZE;
    private static Integer QUEUE_CAPACITY;
    private static Long KEEP_ALIVE_SECONDS;
    @PostConstruct
    public void init() {
        System.out.println("初始化线程池");
        CORE_POOL_SIZE  =this.corePoolSize;
        MAX_POOL_SIZE  =this.maxPoolSize;
        QUEUE_CAPACITY  =this.queueCapacity;
        KEEP_ALIVE_SECONDS  =this.keepAliveSeconds;
    }

    private static ThreadPoolExecutor executor;
    public static ThreadPoolExecutor getExecutor() {
        if (executor != null) {
            return executor;
        }
        synchronized (ServiceThreadPoolConfig.class) {
            if (executor != null) {
                return executor;
            }
            executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_SECONDS,
                    TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY)
                    , Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()
            );
            return executor;
        }
    }
}
